import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
import { Form, message, Popconfirm, Button, Modal, Icon, Upload, Radio, Input } from 'antd'
import { widgetType } from 'constants'
import PropTypes from 'prop-types'
import Style from './manage.css'

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}
class RecycleForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getEcGoodsList: PropTypes.func,
    ecGoods: PropTypes.object
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      editParams: {},
      coverImg: {},
      imageList: []
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.handleEdit = this.handleEdit.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.handleOk = this.handleOk.bind(this)
    this.onChange = this.onChange.bind(this)
    this.firstImageChange = this.firstImageChange.bind(this)
  }

  getFilterCols (category, author) {
    return [
      {
        label: '输入搜索',
        id: 'name',
        widget: widgetType.input,
        placeholder: '请输入商品名称'
      }, {
        label: false,
        span: 16,
        key: 'custom',
        widget: 'custom',
        formItemLayout: {},
        render: () => {
          return (
            <>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.search}>查询</Button>
              <Button style={{ marginRight: 10 }} onClick={this.reset}>重置</Button>
              <Button type='primary' onClick={this.handleAdd}>添加</Button>
            </>
          )
        }
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '商品编号',
        dataIndex: 'code',
        key: 'code',
        width: 100
      }, {
        title: '商品名称',
        dataIndex: 'name',
        key: 'name',
        width: 100
      }, {
        title: '商品图片',
        dataIndex: 'image',
        key: 'image',
        width: 100,
        render: text => <img className={Style['image']} src={text} />
      }, {
        title: '商品对应积分',
        dataIndex: 'integration',
        key: 'integration',
        width: 100,
        sorter: (a, b) => a.integration - b.integration
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <>
            <div>
              <Popconfirm placement='top' title={`确认是否${record.isShelf === '1' ? '下架' : '上架'}`} onConfirm={() => this.handleUpdate(record)}>
                <a className={Style['a-btn']}>{record.isShelf === '1' ? '下架' : '上架'}</a>
              </Popconfirm>
              <a className={Style['a-btn']} onClick={() => this.handleEdit(record)}>编辑</a>
            </div>
            <div>
              <Popconfirm placement='top' title='确认是否删除' onConfirm={() => this.handleDelete(record.exchangeCommodityId)}>
                <a className={Style['a-btn']}>删除</a>
              </Popconfirm>
              {/* <a className={Style['a-btn']}>详情</a> */}
            </div>
          </>
        },
        width: 100
      }
    ]
  }

  handleCancel () {
    this.setState({
      showModal: false
    })
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    const { form } = this.props
    form.resetFields()
    this.props.getEcGoodsList({
      pageNo: 1,
      pageSize: 20
    })
  }
  search (values = {}) {
    const { pageSize, pageNo } = this.state
    let params = {
      pageSize, pageNo
    }
    // eslint-disable-next-line handle-callback-err
    this.props.form.validateFieldsAndScroll((err, values) => {
      params.name = values.name
      this.setState({
        params
      })
      this.props.getEcGoodsList(params)
    })
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    this.props.getEcGoodsList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    this.props.getEcGoodsList(params)
  }

  // 删除
  handleDelete (id) {
    this.props.delEcGoods({
      exchangeCommodityId: id
    })
  }

  handleUpdate (row) {
    this.props.updateEcGoods({
      isShelf: row.isShelf === '1' ? 0 : 1,
      exchangeCommodityId: row.exchangeCommodityId
    })
  }

  handleEdit (row) {
    this.props.getEcGoodsDetails({
      exchangeCommodityId: row.exchangeCommodityId
    })
    this.setState({
      showModal: true,
      status: 'edit',
      title: '编辑兑换商品',
      editParams: row
    })
  }

  handleAdd () {
    this.setState({
      showModal: true,
      status: 'add',
      title: '添加兑换商品'
    })
  }

  handleOk () {
    const { coverImg, imageList, status, editParams } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.imageList = [coverImg, ...imageList]
        values.name = values.goodsName
        delete values.goodsName
        delete values.avatar
        if (status === 'edit') {
          values.id = editParams.exchangeCommodityId
          this.props.editEcGoods(values)
        } else {
          this.props.addEcGoods(values)
        }
      }
    })
  }

  beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG/PNG格式的图片!')
      this.setState({
        loading: false
      })
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 64
    if (!isLt2M) {
      message.error('图片大小 64MB!')
      this.setState({
        loading: false
      })
      return false
    }
    return isJpgOrPng && isLt2M
  }

  onChange ({ file, fileList, event }) {
    const { imageList } = this.state
    let imageArr = []
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      this.setState({
        loading: false
      })
      message.error('上传失败')
    }

    if (file.status === 'done') {
      if (imageList.length < 5) {
        imageArr.push({
          imageUrl: file.response && file.response.data.imageUrl,
          width: file.response && file.response.data.width,
          height: file.response && file.response.data.height,
          cover: 0
        })
      } else {
        message.warning('最多上传5张图片')
      }
      this.setState({
        loading: false,
        imageList: imageList.concat(imageArr)
      })
    }

    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  handleClose (index) {
    const { imageList } = this.state
    const imageCp = imageList.slice(0, imageList.length)
    imageCp.splice(index, 1)
    this.setState({
      imageList: imageCp
    })
  }

  firstImageChange ({ file, fileList, event }) {
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      message.error('上传失败')
      this.setState({
        loading: false
      })
      return
    }

    if (file.status === 'done') {
      this.setState({
        loading: false,
        coverImg: {
          imageUrl: file.response && file.response.data.imageUrl,
          width: file.response && file.response.data.width,
          height: file.response && file.response.data.height,
          cover: 1
        }
      })
    }

    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  componentDidMount () {
    const { pageSize, pageNo } = this.state
    this.props.getEcGoodsList({
      pageSize,
      pageNo
    })
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.addEcGoodsRequest && nextProps.addEcGoodsRequest) {
      message.success('添加成功')
      this.setState({
        showModal: false,
        coverImg: {},
        imageList: []
      })
      this.search()
    }

    if (!this.props.editEcGoodsRequest && nextProps.editEcGoodsRequest) {
      message.success('编辑成功')
      this.setState({
        showModal: false
      })
      this.search()
    }

    if (!this.props.updateEcGoodsRequest && nextProps.updateEcGoodsRequest) {
      message.success('操作成功')
      this.search()
    }

    if (!this.props.delEcGoodsRequest && nextProps.delEcGoodsRequest) {
      message.success('删除成功')
      this.search()
    }

    if (!this.props.ecGoodsDetails && nextProps.ecGoodsDetails) {
      this.setState({
        coverImg: nextProps.ecGoodsDetails.coverImg,
        imageList: nextProps.ecGoodsDetails.imageList
      })
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { pageNo, pageSize, coverImg, imageList, loading, showModal, title, status, editParams } = this.state
    const { form, ecGoods } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: ecGoods && ecGoods.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }

    const uploadButton = (
      <div className={Style[`${coverImg.imageUrl ? '' : 'image-container'}`]}>
        {
          (coverImg.imageUrl || editParams.image) ? <div className={Style['upload-image']} style={{ backgroundImage: `url(${coverImg.imageUrl || editParams.image})` }} /> : <>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className={Style['ant-upload-text']}>Upload</div></>
        }
      </div>
    )

    return (
      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Filters
              cols={this.getFilterCols()}
              form={form}
              search={this.search}
              reset={this.reset}
              actions={false}
            >
              {/* <Button type='primary' onClick={this.handleAdd}>添加</Button> */}
            </Filters>
            <CustomTable
              loading={!ecGoods} columns={this.getTableCols()}
              dataSource={(ecGoods && ecGoods.list) || []}
              pagination={pagination} />
            <Modal
              title={title}
              visible={showModal}
              width={1050}
              onOk={this.handleOk}
              destroyOnClose
              onCancel={this.handleCancel}
            >
              <Form {...formItemLayout}>
                {
                  status === 'edit' && <Form.Item label='商品编号'>
                    {getFieldDecorator('code', {
                      rules: [{ required: true, message: '请输入商品编号' }],
                      initialValue: editParams.code
                    })(
                      <Input placeholder='请输入' disabled style={{ width: '260px' }} />
                    )}
                  </Form.Item>
                }
                <Form.Item label='商品名称'>
                  {getFieldDecorator('goodsName', { rules: [{ required: true, message: '请输入商品名称' }], initialValue: editParams.name })(
                    <Input placeholder='请输入' style={{ width: '260px' }} />
                  )}
                </Form.Item>
                <Form.Item label='商品介绍'>
                  {getFieldDecorator('productIntroduce', { rules: [{ required: true, message: '请输入商品介绍' }], initialValue: editParams.productIntroduce })(
                    <Input placeholder='请输入' style={{ width: '260px' }} />
                  )}
                </Form.Item>
                <Form.Item label='对应积分'>
                  {getFieldDecorator('integration', { rules: [{ required: true, message: '请输入对应积分' }], initialValue: editParams.integration })(
                    <Input placeholder='请输入' type='number' style={{ width: '260px' }} />
                  )}
                </Form.Item>
                <Form.Item label='商品库存'>
                  {getFieldDecorator('stock', { rules: [{ required: true, message: '请输入库存' }], initialValue: editParams.stock })(
                    <Input placeholder='请输入' type='number' style={{ width: '260px' }} />
                  )}
                </Form.Item>
                <Form.Item label='商品封面' extra={<span style={{ fontSize: '14px', color: 'rgba(0, 0, 0, 0.35)' }}>只能上传jpg/png格式，图片大小限定1～3M</span>}>
                  {getFieldDecorator('avatar', {
                    valuePropName: 'picture',
                    initialValue: editParams.image,
                    rules: [{ required: true, message: '请选上传商品封面' }]
                  })(
                    <Upload
                      action='/file/upload/1.0'
                      name='file'
                      onChange={this.firstImageChange}
                      showUploadList={false}
                      withCredentials
                      beforeUpload={this.beforeUpload}
                      headers={{
                        token: localStorage.getItem('token') || ''
                      }}
                    >
                      {uploadButton}
                      <Button type='primary'>
                        <Icon type='cloud-upload' /> 选择上传图片
                      </Button>
                    </Upload>
                  )}

                </Form.Item>
                <Form.Item label='商品图片'>
                  <div className={Style['image-list']}>
                    {
                      imageList.map((item, index) => <div key={index} className={Style['goods-image-container']}>
                        <div className={Style['goods-image']} style={{ backgroundImage: `url(${item.imageUrl})` }} >
                          <Icon type='close-circle' className={Style['close']} onClick={() => this.handleClose(index)} />
                        </div>
                      </div>)
                    }
                  </div>
                </Form.Item>
                <Form.Item wrapperCol={{ span: 12, offset: 5 }} help='最多可以上传5张图片，封面图片限定尺寸900:600'>
                  <Upload
                    action='/file/upload/1.0'
                    name='file'
                    onChange={this.onChange}
                    beforeUpload={this.beforeUpload}
                    showUploadList={false}
                    withCredentials
                    multiple
                    headers={{
                      token: localStorage.getItem('token') || ''
                    }}
                  >
                    <Button type='primary'>
                      <Icon type='cloud-upload' /> 选择上传图片
                    </Button>
                  </Upload>
                </Form.Item>
                <Form.Item label='是否上架'>
                  {getFieldDecorator('isShelf', {
                    valuePropName: 'radio',
                    initialValue: 1
                  })(
                    <Radio.Group defaultValue={1}>
                      <Radio value={1}>是</Radio>
                      <Radio value={0}>否</Radio>
                    </Radio.Group>)}
                </Form.Item>
              </Form>
            </Modal>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  ecGoods: state.exchange.ecGoods,
  updateEcGoodsRequest: state.exchange.updateEcGoodsRequest,
  delEcGoodsRequest: state.exchange.delEcGoodsRequest,
  addEcGoodsRequest: state.exchange.addEcGoodsRequest,
  editEcGoodsRequest: state.exchange.editEcGoodsRequest,
  ecGoodsDetails: state.exchange.ecGoodsDetails
})
const mapDispatch = dispatch => ({
  getEcGoodsList: dispatch.exchange.getEcGoodsList,
  delEcGoods: dispatch.exchange.delEcGoods,
  updateEcGoods: dispatch.exchange.updateEcGoods,
  addEcGoods: dispatch.exchange.addEcGoods,
  editEcGoods: dispatch.exchange.editEcGoods,
  getEcGoodsDetails: dispatch.exchange.getEcGoodsDetails
})

const Recycle = Form.create()(RecycleForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Recycle)
)
